package leetcode;

import java.net.URLClassLoader;
import java.util.HashMap;

public class Lc128 {


    public int longestConsecutive(int[] nums) {
        if (nums.length == 0 || nums.length == 1) return nums.length;
        HashMap<Integer, Integer> map = new HashMap();
        UnionFindSet128 ufs = new UnionFindSet128(nums.length);
        for (int i = 0; i < nums.length; i++) {
            map.put(nums[i], i);
        }
        for (int i = 0; i < nums.length; i++) {
            int num = nums[i];
            if (map.containsKey(num - 1)) {
                ufs.union(map.get(num), map.get(num - 1));
            }
            if (map.containsKey(num + 1)) {
                ufs.union(map.get(num), map.get(num + 1));
            }
        }
        return ufs.getMaxRank();
    }
}
class UnionFindSet128 {

    int[] parent;
    int[] rank;
    int maxRank;
    public UnionFindSet128(int n) {
        parent = new int[n];
        rank = new int[n];
        maxRank = 1;
        for (int i = 0; i < n; i++) {
            parent[i] = i;
            rank[i] = 1;
        }
    }

    public int find(int x) {
        if (x != parent[x]) {
            parent[x] = find(parent[x]);
        }
        return parent[x];
    }

    public void union(int x, int y) {
        int xParent = find(x);
        int yParent = find(y);
        if (xParent != yParent) {
            if (rank[xParent] < rank[yParent]) {
                parent[xParent] = yParent;
                rank[yParent] += rank[xParent];
                maxRank = Math.max(maxRank, rank[yParent]);
            } else {
                parent[yParent] = xParent;
                rank[xParent] += rank[yParent];
                maxRank = Math.max(maxRank, rank[xParent]);
            }
        }
    }
    public int getMaxRank() {
        return maxRank;
    }
}